import requests
from lxml import html

def work(url):
    """返回新界面xpath对象"""
    # 设置请求头，模拟浏览器访问，避免被反爬
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Refer': ''
    }
    response = requests.get(url, headers=headers)
    # 检查请求是否成功
    if response.status_code == 200:
        html_content = response.text  # 获取HTML文本
        tree = html.fromstring(html_content)
        return tree

    else:
        print(f"请求失败，状态码: {response.status_code}")
        return None
        # 处理错误...


def print_info(info, head):
    print(head + ":", end=" ")
    has_content = False  # 标记是否有有效内容

    for line in info:
        # 特别处理日期情况
        if head == "日期":
            if isinstance(line, list) and len(line) > 0:
                print(line[0], end=" ")
                has_content = True
            elif not isinstance(line, list) and line:
                print(line, end=" ")
                has_content = True
        else:
            # 其他情况只打印非空内容
            if line:  # 只有当line非空时才打印
                print(line, end=" ")
                has_content = True

    # 如果没有有效内容，输出"未知"
    if not has_content:
        print("未知", end=" ")

    print()

def main():
    url = 'https://movie.douban.com/chart'
    tree = work(url)
    infos = tree.xpath('//div[@class="pl2"]')

    print("*" * 40)

    for info in infos:
        # print(info)
        new_url = info.xpath('./a/@href')[0]
        new_tree = work(new_url)
        mov_content = new_tree.xpath('//div[@id="content"]')


        title = mov_content[0].xpath('//h1/span[1]/text()')
        # print(title)
        print_info(title, "电影名")

        mov_info = mov_content[0].xpath('//div[@class="subject clearfix"]'
                                        '/div[@id="info"]/span')
        score_info = mov_content[0].xpath('//div[@id="interest_sectl"]'
                                           '/div[@class="rating_wrap clearbox"]')
        # 导演
        actor = mov_info[0].xpath('span[@class="attrs"]/a/text()')
        # print(actor)
        print_info(actor, "导演")
        # 编辑
        playwright = mov_info[1].xpath('span[@class="attrs"]/a/text()')
        # print(playwright)
        print_info(playwright, "编辑")
        # 主演
        actress = mov_info[2].xpath('span[@class="attrs"]/a/text()')
        # print(actress)
        print_info(actress, "主演")

        # mov_type = mov_info[3].xpath('span[@class="attrs"]/a/text()')
        # print(mov_type)
        # 日期
        date1 = mov_content[0].xpath('//div[@class="subject clearfix"]'
                                        '/div[@id="info"]/span[@property="v:initialReleaseDate"][1]/text()')
        date2 = mov_content[0].xpath('//div[@class="subject clearfix"]'
                                        '/div[@id="info"]/span[@property="v:initialReleaseDate"][2]/text()')
        # print(date1)
        # print(date2)
        print_info([date1, date2], "日期")


        # print(score_info)
        # 评分
        score = score_info[0].xpath('div[@class="rating_self clearfix"]/strong/text()')
        # print(score)
        print_info(score, "评分")

        vote_num = score_info[0].xpath('div[@class="rating_self clearfix"]'
                                       '/div[@class="rating_right "]'
                                       '/div[@class="rating_sum"]'
                                       '/a/span/text()')
        # print(vote_num)
        # print_info(vote_num, "")

        # 短评
        short_remark = mov_content[0].xpath('//div[@class="mod-hd"]/h2/i/text()') + mov_content[0].xpath('//div[@class="mod-hd"]/h2/span/a/text()')
        # print(short_remark)
        print_info(short_remark, "短评")

        print("*"*40)

main()
